package generalEvolutionaryAlgorithm;

import java.util.LinkedList;
import java.util.List;
import java.util.Random;

public class EASelectionSurvivalOfTheFittestRandomTournament implements EASelection{
	private int maximalSurvivors;
	Random rand;
	public EASelectionSurvivalOfTheFittestRandomTournament(int maximalSurvivors){
		this.maximalSurvivors = maximalSurvivors;
		rand = new Random();
	}
	@Override
	public List<EAInstance> selection(List<EAInstance> population) {
		Object[] instancesO = population.toArray();
		EAInstance[] instances = new EAInstance[instancesO.length];
		for(int i = 0; i < instances.length; i++){
			instances[i] = (EAInstance) instancesO[i];
		}
		int n = instances.length;
		while(n > maximalSurvivors){
			int i = Math.abs(rand.nextInt()) % n;
			int j = Math.abs(rand.nextInt()) % n;
			if(i == j)continue;
			if(instances[i].getResult().optimalValue == null){
				instances[i].calculateResult();
			}
			if(instances[j].getResult().optimalValue == null){
				instances[j].calculateResult();
			}
			EAResult bestRes = EAResult.best(instances[i].getResult(), instances[j].getResult());
			int remove = j;
			if(bestRes.equals(instances[j].getResult())){
				remove = i;
			}
			instances[remove] = instances[--n];
		}
		LinkedList<EAInstance> list = new LinkedList<EAInstance>();
		for(int i = 0; i < n; i++){
			list.add(instances[i]);
		}
		return list;
	}
	
}
